﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace RobotEscape
{
    public static class KeyState
    {
        // Only support the "standard" keys
        private const int MAX_KEYS = 256;

        // The state of each key is held in this array
        private static bool[] states = new bool[MAX_KEYS];
        private static bool[] oldstates = new bool[MAX_KEYS];

        public static bool GetKeyState(Key key)
        {
            int index = (int)key;
            if (index < 0 || index >= MAX_KEYS) return false;
            return states[index];
        }

        public static bool GetOldKeyState(Key key)
        {
            int index = (int)key;
            if (index < 0 || index >= MAX_KEYS) return false;
            return oldstates[index];
        }

        public static bool GetNewlyPressedKey(Key key)
        {
            return (GetKeyState(key) && !GetOldKeyState(key));
        }

        public static void HookEvents(UIElement elem)
        {
            elem.KeyDown += OnKeyDown;
            elem.KeyUp += OnKeyUp;
        }

        public static void UnhookEvents(UIElement elem)
        {
            elem.KeyDown -= OnKeyDown;
            elem.KeyUp -= OnKeyUp;
        }

        public static void Update()
        {
            for (int i = 0; i < states.Length; i++)
            {
                oldstates[i] = states[i];
            }
        }

        private static void OnKeyUp(object sender, KeyEventArgs e)
        {
            states[(int)e.Key] = false;
        }

        private static void OnKeyDown(object sender, KeyEventArgs e)
        {
            states[(int)e.Key] = true;
        }
    }
}
